package middleware

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/utils/tenant_common"
	"git.myscrm.cn/golang/common/ykerrcode"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

func TenantDb() gin.HandlerFunc {
	return func(c *gin.Context) {
		var db *gorm.DB
		var err error
		// gin请求即将结束前，释放db连接
		defer func() {
			if db == nil {
				return
			}

			sqlDB, err := db.DB()
			if err == nil && sqlDB != nil {
				_ = sqlDB.Close()
			}
		}()
		c.Set(tenant_common.TENANT_CODE, c.GetHeader(tenant_common.TENANT_CODE))
		// 注意，不能用 := 否则变成临时变量
		c, db, err = tenant_common.GetTenantDBAndGinContext(c)
		if err != nil {
			c.Abort()
			grpcErr := rpc_client.GetGrpcError(err)
			errCode := ykerrcode.DB_ERR
			if grpcErr.GetCode() != 0 {
				errCode = grpcErr.GetCode()
			}
			result := map[string]interface{}{
				"success":    false,
				"message":    common.WrapError(err.Error()),
				"error_code": errCode,
				"data":       nil,
			}
			c.JSON(http.StatusOK, result)
			return
		}
		c.Next()
	}
}
